<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="机构名称">
        <el-input
          v-model="searchObj.userName"
          placeholder="请输入机构名称"
          clearable
          @change="fetchData()"
          @keyup.enter="fetchData()"
        />
      </el-form-item>

      <el-form-item label="用户账号" label-width="160px">
        <el-input
          v-model="searchObj.userAccount"
          placeholder="请输入用户账号"
          clearable
          @change="fetchData()"
          @keyup.enter="fetchData()"
        />
      </el-form-item>

      <!--      <el-form-item label="创建时间">-->
      <!--        <el-date-picker-->
      <!--          v-model="searchObj.gmtCreate"-->
      <!--          type="datetime"-->
      <!--          placeholder="选择创建时间"-->
      <!--          value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--          default-time="00:00:00"-->
      <!--          @change="fetchData()"-->
      <!--        />-->
      <!--      </el-form-item>-->

      <!--      <el-form-item label="更新时间">-->
      <!--        <el-date-picker-->
      <!--          v-model="searchObj.gmtModified"-->
      <!--          type="datetime"-->
      <!--          placeholder="选择更新时间"-->
      <!--          value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--          default-time="00:00:00"-->
      <!--          @change="fetchData()"-->
      <!--        />-->
      <!--      </el-form-item>-->

      <el-form-item label="机器码" label-width="145px">
        <el-input
          v-model="searchObj.uniqueCode"
          placeholder="请输入机器码"
          clearable
          @change="fetchData()"
          @keyup.enter="fetchData()"
        />
      </el-form-item>
      <br>

      <el-form-item label="到期时间：">
        <el-radio-group v-model="searchObj.validity" @change="fetchData()">
          <el-radio :label="-1">全部</el-radio>
          <el-radio :label="0">3天以内</el-radio>
          <el-radio :label="1">3-7天</el-radio>
          <el-radio :label="2">7-15天</el-radio>
          <el-radio :label="3">15天以上</el-radio>
        </el-radio-group>
      </el-form-item>

      <br>
      <el-form-item label="到期状态：">
        <el-radio-group v-model="searchObj.expireStatus" @change="fetchData()">
          <el-radio :label="-1">全部</el-radio>
          <el-radio :label="0">未到期</el-radio>
          <el-radio :label="1">已到期</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="登录状态：" label-width="200px">
        <el-radio-group v-model="searchObj.loginStatus" @change="fetchData()">
          <el-radio :label="-1">全部</el-radio>
          <el-radio :label="0">未登录</el-radio>
          <el-radio :label="1">已登录</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="删除状态：" label-width="200px">
        <el-radio-group v-model="searchObj.isDeleted" @change="fetchData()">
          <el-radio :label="-1">全部</el-radio>
          <el-radio :label="0">未删除</el-radio>
          <el-radio :label="1">已删除</el-radio>
        </el-radio-group>
      </el-form-item>
      <br>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="fetchData">
          查询
        </el-button>
        <el-button type="primary" icon="el-icon-delete" size="small" @click="resetData">
          重置
        </el-button>
      </el-form-item>

      <span style="line-height: 0px; margin-left: 1385px">
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="dialogInsertVisable = true">
          新增
        </el-button>
      </span>

    </el-form>

    <!-- 新增信息弹窗 -->
    <el-dialog title="新增用户信息" :visible.sync="dialogInsertVisable" @close="closeInsertVisable('insertObj')">
      <el-form ref="insertObj" :model="insertObj" label-width="100px" class="demo-form-inline" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="机构名称" prop="userName">
              <el-input v-model="insertObj.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="用户账号" prop="userAccount">
              <el-input v-model="insertObj.userAccount" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="insertObj.password">
                <el-button
                  slot="append"
                  type="primary"
                  size="medium"
                  icon="el-icon-key"
                  @click="initPassword(insertObj.userAccount)"
                >
                  生成密码
                </el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="机器码" prop="uniqueCode">
              <el-input v-model="insertObj.uniqueCode" :disabled="false" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="到期时间" prop="expireTime">
              <el-date-picker
                v-model="insertObj.expireTime"
                :picker-options="optionsDisable"
                type="date"
                placeholder="选择到期时间"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                @change="dateChangeByPicker()"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="剩余天数" prop="validity">
              <el-input-number
                v-model="insertObj.validity"
                :min="0"
                :max="999"
                @change="dateChangeByInput()"
                @keyup.enter="dateChangeByInput()"
              >
                <div slot="append">天</div>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="insertObj.remarks" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogInsertVisable = false">
          取消
        </el-button>
        <el-button type="primary" @click="insertSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!--列表 height="600"-->
    <el-table :data="list" border stripe>
      <el-table-column label="序号" width="50">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="userName" label="机构名称" />
      <el-table-column prop="userAccount" label="用户账号" />
      <el-table-column prop="uniqueCode" label="机器码" />
      <!--      <el-table-column prop="loginStatus" label="登录状态">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-tag v-if="scope.row.loginStatus === 1" type="success" size="mini">-->
      <!--            已登录-->
      <!--          </el-tag>-->
      <!--          <el-tag v-else type="info" size="mini">-->
      <!--            未登录-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column prop="expireStatus" label="到期状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.validity === 0" type="danger" size="mini">
            已到期
          </el-tag>
          <el-tag v-else type="info" size="mini">
            未到期
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="expireTime" label="账号到期时间" />
      <el-table-column prop="validity" label="剩余天数">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.validity != null && scope.row.validity <= 3" type="danger" size="mini">
            {{ scope.row.validity }}天
          </el-tag>
          <el-tag v-if="scope.row.validity > 3 && scope.row.validity <= 7" type="warning" size="mini">
            {{ scope.row.validity }}天
          </el-tag>
          <el-tag v-if="scope.row.validity > 7 && scope.row.validity <= 15" type="info" size="mini">
            {{ scope.row.validity }}天
          </el-tag>
          <el-tag v-if="scope.row.validity > 15" type="success" size="mini">
            {{ scope.row.validity }}天
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" />
      <!--      <el-table-column prop="gmtCreate" label="创建时间" />-->
      <!--      <el-table-column prop="gmtModified" label="更新时间" />-->

      <!--      <el-table-column label="是否已删除" width="90">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-tag v-if="scope.row.isDeleted === 1" type="danger" size="mini">-->
      <!--            已删除-->
      <!--          </el-tag>-->
      <!--          <el-tag v-else type="info" size="mini">-->
      <!--            未删除-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.isDeleted === 0"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editById(scope.row.id)"
          >
            修改
          </el-button>
          <el-button
            v-if="scope.row.isDeleted === 0"
            type="warning"
            size="mini"
            icon="el-icon-delete"
            @click="removeById(scope.row.id)"
          >删除
          </el-button>
          <el-button
            v-if="scope.row.isDeleted === 1"
            type="success"
            size="mini"
            icon="el-icon-edit"
            @click="resumeById(scope.row.id)"
          >
            恢复
          </el-button>
          <el-button
            v-if="scope.row.isDeleted === 1"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="foreverRemove(scope.row.id)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改信息弹窗 -->
    <el-dialog title="修改用户信息" :visible.sync="dialogTableVisible" width="1000px" @close="closeDetailVisable('detailObj')">
      <el-form ref="detailObj" :model="detailObj" label-width="100px" class="demo-form-inline" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="机构名称" prop="userName">
              <el-input v-model="detailObj.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="用户账号" prop="userAccount">
              <el-input v-model="detailObj.userAccount" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="detailObj.password">
                <el-button
                  slot="append"
                  type="primary"
                  size="medium"
                  icon="el-icon-key"
                  @click="initPassword(detailObj.userAccount)"
                >
                  生成密码
                </el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="机器码" prop="uniqueCode">
              <el-input v-model="detailObj.uniqueCode" :disabled="false" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="到期时间" prop="expireTime">
              <el-date-picker
                v-model="detailObj.expireTime"
                :picker-options="optionsDisable"
                type="date"
                placeholder="选择到期时间"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                @change="dateChangeByPicker()"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="剩余天数" prop="validity">
              <el-input-number
                v-model="detailObj.validity"
                :min="0"
                :max="999"
                @change="dateChangeByInput()"
                @keyup.enter="dateChangeByInput()"
              >
                <div slot="append">天</div>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="detailObj.remarks" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false; detailObj = {}">
          取消
        </el-button>
        <el-button type="primary" @click="detailSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[10, 20]"
      style="padding: 30px 0; "
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="changePageSize"
      @current-change="changeCurrentPage"
    />

  </div>
</template>

<script>
import userInfoApi from '@/api/userInfo/userInfo'

export default {
  name: 'UserInfoList',
  data() {
    const validate1 = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error('请输入剩余天数'))
      } else if (value < 0) {
        callback(new Error('剩余天数不能小于0'))
      } else if (value > 999) {
        callback(new Error('剩余天数不能大于999'))
      } else {
        callback()
      }
    }
    return {
      list: null, // 数据列表
      total: 0, // 数据库总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      // 查询条件
      searchObj: {
        validity: -1,
        expireStatus: -1,
        loginStatus: -1,
        isDeleted: 0
      },
      // 修改条件
      detailObj: {
        userName: '',
        userAccount: '',
        password: '',
        uniqueCode: '',
        expireTime: null,
        validity: 0,
        remarks: ''
      },
      // 新增条件
      insertObj: {
        userName: '',
        userAccount: '',
        password: '',
        uniqueCode: '',
        expireTime: null,
        validity: 0,
        remarks: ''
      },
      dialogTableVisible: false, // 修改对话框是否显示
      dialogInsertVisable: false, // 新增对话框是否显示
      optionsDisable: { // 时间控件范围
        disabledDate: this.disabledDate
      },
      rules: {
        userName: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
        userAccount: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入用户密码', trigger: 'change' }],
        uniqueCode: [{ required: true, message: '请输入机器码', trigger: 'blur' }],
        expireTime: [{ type: 'string', required: true, message: '请输入到期时间', trigger: 'change' }],
        validity: [{ required: true, validator: validate1, trigger: 'change' }]
      }

    }
  },

  created() {
    this.fetchData()
  },

  methods: {
    fetchData() {
      userInfoApi.listPage(this.page, this.limit, this.searchObj).then((response) => {
        this.list = response.data.result.list
        this.total = response.data.result.total
      })
    },

    fetchDataById(id) {
      userInfoApi.getInfoById(id).then((response) => {
        this.detailObj = response.data.result
      })
    },

    // 每页展示条数的改变，size：回调函数, 表示当前选中的展示条数
    changePageSize(size) {
      this.limit = size
      this.fetchData()
    },

    // 翻页，page：回调函数, 表示当前选中的页码
    changeCurrentPage(page) {
      this.page = page
      this.fetchData()
    },

    // 重置搜索表单
    resetData() {
      this.searchObj = {}
      this.searchObj.expireStatus = -1
      this.searchObj.loginStatus = -1
      this.searchObj.validity = -1
      this.searchObj.isDeleted = 0
      this.fetchData()
    },

    // 关闭新增弹窗
    closeInsertVisable(insertObj) {
      this[insertObj] = {
        userName: '',
        userAccount: '',
        password: '',
        uniqueCode: '',
        expireTime: null,
        validity: 0,
        remarks: ''
      }
      this.$nextTick(() => {
        this.$refs[insertObj].clearValidate()
      })
    },

    // 新增
    insertSubmit() {
      this.$refs.insertObj.validate(valid => {
        if (valid) {
          userInfoApi.insertUserInfo(this.insertObj).then((response) => {
            this.$message.success(response.message)
            this.fetchData()
          }).catch(() => {
            this.$message.error('新增失败')
          })
          this.dialogInsertVisable = false
        } else {
          return false
        }
      })
    },

    // 修改用户信息对话框
    editById(id) {
      // 根据id查询数据
      this.fetchDataById(id)

      // 打开对话框
      this.dialogTableVisible = true
    },

    // 关闭修改弹窗
    closeDetailVisable(detailObj) {
      this[detailObj] = {
        userName: '',
        userAccount: '',
        password: '',
        uniqueCode: '',
        expireTime: null,
        validity: 0,
        remarks: ''
      }
      this.$nextTick(() => {
        this.$refs[detailObj].clearValidate()
      })
    },

    // 修改用户信息
    detailSubmit(id) {
      this.$refs.detailObj.validate(valid => {
        if (valid) {
          userInfoApi.updateById(this.detailObj).then((response) => {
            this.$message.success(response.message)
            this.fetchData()
          }).catch(() => {
            this.$message.error('修改失败')
          })
          this.dialogTableVisible = false
        } else {
          return false
        }
      })
    },

    // 删除用户信息
    removeById(id) {
      this.$confirm('是否删除该记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'waring'
      })
        .then(() => {
          userInfoApi.removeById(id).then(response => {
            this.$message.success(response.message)
            this.fetchData()
          })
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },

    // 恢复用户信息
    resumeById(id) {
      this.$confirm('是否恢复该记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'waring'
      })
        .then(() => {
          userInfoApi.resumeById(id).then(response => {
            this.$message.success(response.message)
            this.fetchData()
          })
        })
        .catch(() => {
          this.$message.info('取消恢复')
        })
    },

    // 永久删除用户信息
    foreverRemove(id) {
      this.$confirm('此操作将永久删除该记录且无法恢复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'waring'
      })
        .then(() => {
          userInfoApi.foreverRemove(id).then(response => {
            this.$message.success(response.message)
            this.fetchData()
          })
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },

    // 生成密码
    initPassword(userAccount) {
      const params = {
        userAccount: userAccount
      }
      userInfoApi.initPassword(params).then((response) => {
        this.detailObj.password = response.data.result
        this.insertObj.password = response.data.result
      }).catch(() => {
        this.$message.error('生成失败')
      })
    },

    // 时间控件范围
    disabledDate(time) {
      return time.getTime() < Date.now()
    },

    // 根据输入框改变日期选择器
    dateChangeByInput() {
      let value = ''
      if (this.dialogTableVisible) { // 根据打开的弹窗判断是新增还是修改
        value = this.detailObj.validity
      } else {
        value = this.insertObj.validity
      }

      if (value === undefined) { // 如果清空输入框，则同步清空日期框
        this.detailObj.expireTime = null
        this.insertObj.expireTime = null
        return
      }
      if (value < 0) {
        let nowDate = new Date()
        nowDate = nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1) + '-' + nowDate.getDate() + ' '
        this.detailObj.expireTime = nowDate
        this.insertObj.expireTime = nowDate
        return
      }

      let nowDate = new Date()
      nowDate = nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1) + '-' + nowDate.getDate() + ' ' // 获取当前时间
      nowDate = Date.parse(new Date(nowDate)) / 1000 // 获取当前时间的时间戳
      nowDate += value * 60 * 60 * 24 // 计算时间
      const returnDate = new Date(parseInt(nowDate) * 1000)

      if (this.dialogTableVisible) {
        this.detailObj.expireTime = returnDate.getFullYear() + '-' + (returnDate.getMonth() + 1) + '-' + returnDate.getDate() + ' '
      } else {
        this.insertObj.expireTime = returnDate.getFullYear() + '-' + (returnDate.getMonth() + 1) + '-' + returnDate.getDate() + ' '
      }
    },

    // 根据日期选择器改变输入框
    dateChangeByPicker() {
      let pikerDate = null
      if (this.dialogTableVisible) { // 根据打开的弹窗判断是新增还是修改
        pikerDate = this.detailObj.expireTime
      } else {
        pikerDate = this.insertObj.expireTime
      }

      if (pikerDate === null) { // 如果清空日期框，则同步清空输入框
        this.detailObj.validity = undefined
        this.insertObj.validity = undefined
        return
      }
      let nowDate = new Date()
      nowDate = nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1) + '-' + nowDate.getDate() + ' ' // 获取当前时间
      nowDate = Date.parse(new Date(nowDate)) / 1000 // 获取当前时间的时间戳
      pikerDate = Date.parse(new Date(pikerDate)) / 1000 // 获取日期选择器的时间戳
      nowDate = (pikerDate - nowDate) / (60 * 60 * 24) // 计算差值
      if (this.dialogTableVisible) {
        this.detailObj.validity = nowDate.toFixed(0)
      } else {
        this.insertObj.validity = nowDate.toFixed(0)
      }
    }

  }
}
</script>

<style scoped>

</style>
